import os
import tkinter as tk
from tkinter import Label, ttk
from PIL import Image, ImageTk


class Login(tk.Frame):

    def __init__(self, master=None, title=None, img_dir=None, **kw):
        # 从 kw 中提取变量
        self.login_state = kw.pop('login_state', None)
        self.username_var = kw.pop('username', None)  # 接收外部传入的StringVar
        self.password_var = kw.pop('password', None)  # 接收外部传入的StringVar
        self.codes_var = kw.pop('codes', None)  # 接收外部传入的StringVar
        self.img_dir = img_dir

        super().__init__(master, **kw)
        self.master = master

        # 窗口配置
        screen_width = master.winfo_screenwidth()
        screen_height = master.winfo_screenheight()
        window_width = kw.get('width', 400)
        window_height = kw.get('height', 300)
        x_coordinate = int((screen_width - window_width) / 2)
        y_coordinate = int((screen_height - window_height) / 2)
        master.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")
        master.title(title)

        # 图标加载增加异常处理
        try:
            master.iconbitmap(f'{self.img_dir}/logo.ico')
        except Exception as e:
            print(f"图标加载失败: {e}")

        master.resizable(False, False)
        self.configure(bg='white')
        master.configure(bg='white')
        self.pack(expand=True, fill=tk.BOTH)

        # 样式配置
        style = ttk.Style()
        style.configure("Custom.TFrame", background='white')
        style.configure("Error.TLabel", font=("SimHei", 9), foreground="red", background='white')
        style.configure('TLabel', background='white')
        style.configure('TButton', font=('SimHei', 10))
        style.configure('TEntry', font=('SimHei', 10))

        # 登录框架
        login_frame = ttk.Frame(self, style="Custom.TFrame")
        login_frame.pack(side=tk.TOP, fill=tk.BOTH, padx=20, pady=10)

        # 标题
        title_frame = ttk.Frame(login_frame, style="Custom.TFrame")
        title_frame.pack(side=tk.TOP, fill=tk.X, pady=10)
        title_label = ttk.Label(title_frame, text=title, font=('黑体', 14, 'bold'), style="TLabel")
        title_label.pack(side=tk.BOTTOM, anchor=tk.CENTER)

        # 输入框架
        input_frame = ttk.Frame(login_frame, style="Custom.TFrame")
        input_frame.pack(side=tk.TOP, pady=10)
        input_frame.columnconfigure(0, minsize=60)
        input_frame.columnconfigure(1, weight=1)

        # 用户名输入框 - 关键修复：绑定到StringVar
        username_label = ttk.Label(input_frame, text="账号:", style="TLabel")
        username_label.grid(row=0, column=0, padx=10, pady=10, sticky='e')
        self.username_entry = ttk.Entry(
            input_frame,
            width=20,
            textvariable=self.username_var  # 绑定外部传入的StringVar
        )
        self.username_entry.grid(row=0, column=1, sticky='we', padx=(0, 10))
        self.username_entry.focus()

        # 密码输入框 - 关键修复：绑定到StringVar
        password_label = ttk.Label(input_frame, text="密码:", style="TLabel")
        password_label.grid(row=1, column=0, padx=10, pady=10, sticky='e')
        self.password_entry = ttk.Entry(
            input_frame,
            show="*",
            width=20,
            textvariable=self.password_var  # 绑定外部传入的StringVar
        )
        self.password_entry.grid(row=1, column=1, sticky='we', padx=(0, 10))
        self.password_entry.bind("<Return>", lambda e: self.login())

        # 错误提示
        self.error_label = ttk.Label(login_frame, text='', style="Error.TLabel")
        self.error_label.pack(side=tk.TOP, anchor='w', padx=130, pady=2)

        # 验证码框架
        code_frame = ttk.Frame(login_frame, style="Custom.TFrame")
        code_frame.pack(side=tk.TOP, fill=tk.X, pady=5)

        # 验证码标题
        code_title = ttk.Label(code_frame, style="TLabel")
        code_title.pack(side=tk.LEFT, padx=10, )

        # 验证码图片和输入框
        try:
            img_path = f'{self.img_dir}/登录验证码.png'
            original_img = Image.open(img_path)
            img = original_img.resize((130, 50), Image.LANCZOS)
            self.img_png = ImageTk.PhotoImage(img)
            label_img = Label(code_frame, image=self.img_png, bg="white", bd=0)
            label_img.pack(side=tk.LEFT, padx=5)

            # 验证码输入框 - 关键修复：绑定到StringVar
            self.code_entry = ttk.Entry(
                code_frame,
                width=10,
                textvariable=self.codes_var  # 绑定外部传入的StringVar
            )
            self.code_entry.pack(side=tk.LEFT, padx=10)
            self.code_entry.bind("<Return>", lambda e: self.login())

        except Exception as e:
            print(f"加载验证码图片失败: {e}")
            error_label = ttk.Label(code_frame, text="验证码加载失败", style="Error.TLabel")
            error_label.pack(side=tk.LEFT, padx=10)

        # 按钮布局
        button_frame = ttk.Frame(login_frame, style="Custom.TFrame")
        button_frame.pack(side=tk.BOTTOM, fill=tk.X, pady=20)
        inner_button_frame = ttk.Frame(button_frame, style="Custom.TFrame")
        inner_button_frame.pack(expand=True, fill=tk.X)

        login_button = ttk.Button(inner_button_frame, text="登录", command=self.login)
        login_button.pack(side=tk.LEFT, padx=50)

        cancel_button = ttk.Button(inner_button_frame, text="取消", command=self.cancel)
        cancel_button.pack(side=tk.RIGHT, padx=50)

    def login(self):
        # 清空错误提示
        self.error_label.config(text='')

        # 验证输入不为空
        if not self.username_var.get():
            self.error_label.config(text='❌ 账号不能为空')
            return
        if not self.password_var.get():
            self.error_label.config(text='❌ 密码不能为空')
            return
        if hasattr(self, 'code_entry') and not self.codes_var.get():
            self.error_label.config(text='❌ 验证码不能为空')
            return

        # 登录成功，关闭窗口并更新状态
        self.login_state.set(True)
        self.master.destroy()

    def cancel(self):
        self.login_state.set(False)
        self.master.destroy()


if __name__ == '__main__':
    root = tk.Tk()
    login_state = tk.BooleanVar(root, value=False)
    username = tk.StringVar(root, value='')
    password = tk.StringVar(root, value='')
    codes = tk.StringVar(root, value='')
    app = Login(
        master=root,
        width=400,
        height=350,
        title='运维工具 v0.0.1',
        login_state=login_state,
        username=username,
        password=password,
        codes=codes
    )
    root.mainloop()
    print(f"登录状态: {login_state.get()}")
    print(f"账号: {username.get()}, 密码: {password.get()}, 验证码: {codes.get()}")
